<template>
  <div class="report-analysis">
    <el-card class="box-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <div class="left-section">
            <span class="main-title">审批流程报表分析</span>
            <el-switch
              v-model="autoRefresh"
              class="auto-refresh-switch"
              active-text="自动刷新"
              @change="toggleAutoRefresh"
            />
          </div>
          <div class="right-section">
            <el-date-picker
              v-model="dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="YYYY-MM-DD"
              @change="handleDateChange"
            />
            <el-button type="primary" :icon="Refresh" class="refresh-button" @click="refreshData">
              刷新数据
            </el-button>
          </div>
        </div>
      </template>
      
      <el-row :gutter="20" class="chart-row">
        <el-col :span="8">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span class="chart-title">
                  流程类型分布
                  <el-tooltip content="显示各类流程的数量分布" placement="top">
                    <el-icon><InfoFilled /></el-icon>
                  </el-tooltip>
                </span>
              </div>
            </template>
            <div id="processChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span class="chart-title">
                  审批时效分析
                  <el-tooltip content="展示流程审批耗时统计" placement="top">
                    <el-icon><InfoFilled /></el-icon>
                  </el-tooltip>
                </span>
                <div class="filter-section">
                  <div class="filter-buttons">
                    <el-radio-group v-model="timeChartDimension" size="small" @change="handleDimensionChange">
                      <el-radio-button label="week">本周</el-radio-button>
                      <el-radio-button label="month">本月</el-radio-button>
                      <el-radio-button label="year">本年</el-radio-button>
                    </el-radio-group>
                  </div>
                </div>
              </div>
            </template>
            <div id="timeChart" class="chart-container"></div>
          </el-card>
        </el-col>
        
        <el-col :span="8">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span class="chart-title">
                  审批状态分布
                  <el-tooltip content="显示当前各状态的占比" placement="top">
                    <el-icon><InfoFilled /></el-icon>
                  </el-tooltip>
                </span>
              </div>
            </template>
            <div id="statusChart" class="chart-container"></div>
          </el-card>
        </el-col>
      </el-row>
      
      <el-row class="table-row">
        <el-col :span="24">
          <el-card shadow="hover" class="table-card">
            <template #header>
              <div class="card-header">
                <span class="chart-title">审批流程明细</span>
                <div class="header-operations">
                  <el-input
                    v-model="searchKeyword"
                    placeholder="搜索流程名称/发起人"
                    :prefix-icon="Search"
                    clearable
                    @input="handleSearch"
                    class="search-input"
                  />
                  <el-button type="success" :icon="Download" @click="exportData">
                    导出数据
                  </el-button>
                </div>
              </div>
            </template>
            <el-table 
              :data="tableData" 
              style="width: 100%"
              :stripe="true"
              :border="true"
              height="400"
            >
              <el-table-column prop="processName" label="流程名称" min-width="150" />
              <el-table-column prop="initiator" label="发起人" min-width="120" />
              <el-table-column prop="startTime" label="开始时间" min-width="160" />
              <el-table-column prop="endTime" label="结束时间" min-width="160" />
              <el-table-column prop="duration" label="处理时长" min-width="120" />
              <el-table-column prop="status" label="状态" min-width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.status === '已完成' ? 'success' : 'primary'">
                    {{ scope.row.status }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, onUnmounted, computed } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { InfoFilled, Search, Download, Refresh } from '@element-plus/icons-vue'
import type { EChartsType } from 'echarts'
import baseService from "@/service/baseService";
interface TableItem {
  processName: string
  initiator: string
  startTime: string
  endTime: string
  duration: string
  status: string
}

// 图表实例引用
const processChartRef = ref<EChartsType | null>(null)
const timeChartRef = ref<EChartsType | null>(null)
const statusChartRef = ref<EChartsType | null>(null)

const dateRange = ref<[Date, Date] | null>(null)
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(100)
const tableData = ref<TableItem[]>([])
const loading = ref(false)
const autoRefresh = ref(false)
const timeChartDimension = ref('week')
const timeChartDate = ref<string | null>(null)
let refreshTimer: number | null = null

// 获取日期选择器类型
const getDatePickerType = computed(() => {
  const typeMap = {
    'week': 'date',
    'month': 'month',
    'year': 'year'
  }
  return typeMap[timeChartDimension.value]
})

// 获取日期选择器占位符
const getDatePickerPlaceholder = computed(() => {
  const placeholderMap = {
    'week': '选择日期',
    'month': '选择月份',
    'year': '选择年份'
  }
  return placeholderMap[timeChartDimension.value]
})

// 监听窗口大小变化
const handleResize = () => {
  processChartRef.value?.resize()
  timeChartRef.value?.resize()
  statusChartRef.value?.resize()
}

// 初始化图表
const initCharts = () => {
  initProcessChart()
  initTimeChart()
  initStatusChart()
}

const initProcessChart = () => {
  const chartDom = document.getElementById('processChart')
  if (!chartDom) return
  processChartRef.value = echarts.init(chartDom)
  const option = {
    color: ['#409EFF', '#67C23A', '#E6A23C', '#909399', '#F56C6C'],
    title: {
      left: 'center',
      top: 5,
      textStyle: {
        fontSize: 15,
        color: '#303133',
        fontWeight: 500
      }
    },
    tooltip: {
      trigger: 'item',
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderColor: '#ebeef5',
      borderWidth: 1,
      padding: [8, 10],
      textStyle: {
        color: '#606266',
        fontSize: 13
      },
      formatter: (params: any) => {
        return `<div style="font-weight: 500;margin-bottom:5px;">${params.name}</div>
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
                  <span>数量：</span><span style="font-weight:500;color:#303133">${params.value} 个</span>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
                  <span>占比：</span><span style="font-weight:500;color:#303133">${params.percent}%</span>
                </div>
                <div style="display:flex;justify-content:space-between;align-items:center;">
                  <span>平均耗时：</span><span style="font-weight:500;color:#303133">4.2 小时</span>
                </div>`
      }
    },
    legend: {
      type: 'scroll',
      orient: 'horizontal',
      bottom: 5,
      left: 'center',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 15,
      icon: 'circle',
      pageTextStyle: {
        color: '#909399'
      },
      textStyle: {
        color: '#606266',
        fontSize: 12,
        rich: {
          name: {
            fontSize: 12,
            padding: [0, 4, 0, 0]
          },
          value: {
            fontSize: 12,
            color: '#909399'
          }
        }
      },
      formatter: (name: string) => {
        const data = option.series[0].data
        const item = data.find((i: any) => i.name === name)
        return `{name|${name}} {value|(${item?.value})}`
      }
    },
    series: [
      {
        name: '流程类型',
        type: 'pie',
        radius: ['40%', '70%'],
        center: ['50%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderColor: '#fff',
          borderWidth: 2,
          borderRadius: 5
        },
        label: {
          show: true,
          position: 'outside',
          formatter: '{b}\n{c}个\n{d}%',
          fontSize: 12,
          color: '#606266',
          lineHeight: 15,
          rich: {
            b: {
              fontSize: 12,
              color: '#303133',
              fontWeight: 500,
              padding: [0, 0, 5, 0]
            }
          },
          alignTo: 'none',
          edgeDistance: '5%',
          distanceToLabelLine: 5
        },
        labelLine: {
          show: true,
          length: 10,
          length2: 8,
          minTurnAngle: 90,
          lineStyle: {
            color: '#C0C4CC',
            width: 1
          }
        },
        emphasis: {
          scale: true,
          scaleSize: 5,
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0,0,0,0.2)'
          }
        },
        data: [
          { value: 35, name: '课题申请' },
          { value: 25, name: '经费报销' },
          { value: 20, name: '设备采购' },
          { value: 18, name: '人员调动' },
          { value: 15, name: '其他审批' }
        ]
      }
    ]
  }
  
  processChartRef.value.setOption(option)
}

const initTimeChart = () => {
  updateTimeChart()
}

const initStatusChart = () => {
  const chartDom = document.getElementById('statusChart')
  if (!chartDom) return
  statusChartRef.value = echarts.init(chartDom)

  baseService.get("/process-instance-statistics/statistics").then((res) => {
    if (res.code === 200) {
      const option = {
        color: ['#67C23A', '#409EFF', '#F56C6C'],
        title: {
          text: '',
          left: 'center',
          top: 5
        },
        tooltip: {
          trigger: 'item',
          backgroundColor: 'rgba(255,255,255,0.95)',
          borderColor: '#ebeef5',
          borderWidth: 1,
          padding: [8, 10],
          textStyle: {
            color: '#606266',
            fontSize: 13
          },
          formatter: (params: any) => {
            return `<div style="font-weight: 500;margin-bottom:5px;">${params.name}</div>
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
                      <span>数量：</span><span style="font-weight:500;color:#303133">${params.value} 个</span>
                    </div>
                    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
                      <span>占比：</span><span style="font-weight:500;color:#303133">${params.percent}%</span>
                    </div>`
          }
        },
        legend: {
          type: 'scroll',
          orient: 'horizontal',
          bottom: 5,
          left: 'center',
          itemWidth: 8,
          itemHeight: 8,
          itemGap: 15,
          icon: 'circle',
          pageTextStyle: {
            color: '#909399'
          },
          textStyle: {
            color: '#606266',
            fontSize: 12,
            rich: {
              name: {
                fontSize: 12,
                padding: [0, 4, 0, 0]
              },
              value: {
                fontSize: 12,
                color: '#909399'
              }
            }
          },
          formatter: (name: string) => {
            const data = option.series[0].data
            const item = data.find((i: any) => i.name === name)
            return `{name|${name}} {value|(${item?.value})}`
          }
        },
        series: [
          {
            name: '审批状态',
            type: 'pie',
            radius: ['45%', '70%'],
            center: ['50%', '50%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderColor: '#fff',
              borderWidth: 2,
              borderRadius: 5
            },
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}个\n{d}%',
              fontSize: 12,
              color: '#606266',
              lineHeight: 15,
              rich: {
                b: {
                  fontSize: 12,
                  color: '#303133',
                  fontWeight: 500,
                  padding: [0, 0, 5, 0]
                }
              },
              alignTo: 'none',
              edgeDistance: '5%',
              distanceToLabelLine: 5
            },
            labelLine: {
              show: true,
              length: 10,
              length2: 8,
              minTurnAngle: 90,
              lineStyle: {
                color: '#C0C4CC',
                width: 1
              }
            },
            emphasis: {
              scale: true,
              scaleSize: 5,
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0,0,0,0.2)'
              }
            },
            data: [
              { value: res.data.completed, name: '已完成' },
              { value: res.data.active, name: '进行中' },
              { value: res.data.rejected, name: '已驳回' }
            ]
          }
        ]
      }
      statusChartRef.value.setOption(option)
    }
  })
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    '已完成': 'success',
    '进行中': 'primary',
    '已驳回': 'danger'
  }
  return statusMap[status] || 'info'
}

// 处理日期变化
const handleDateChange = () => {
  refreshData()
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  refreshData()
}

// 处理页码变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  refreshData()
}

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  refreshData()
}

// 导出数据
const exportData = () => {
  loading.value = true
  setTimeout(() => {
    loading.value = false
    ElMessage.success('数据导出成功')
  }, 1000)
}

// 切换自动刷新
const toggleAutoRefresh = () => {
  autoRefresh.value = !autoRefresh.value
  if (autoRefresh.value) {
    refreshTimer = setInterval(refreshData, 30000) // 每30秒刷新一次
    ElMessage.success('已开启自动刷新（30秒）')
  } else {
    if (refreshTimer) {
      clearInterval(refreshTimer)
      refreshTimer = null
    }
    ElMessage.info('已关闭自动刷新')
  }
}

// 刷新数据
const refreshData = () => {
  loading.value = true
  // 模拟API调用
  setTimeout(() => {
    getTableData()
    initCharts()
    loading.value = false
  }, 500)
}

// 获取表格数据
const getTableData = () => {
  loading.value = true
  baseService.get("/process-instance-statistics/summaries", {
    pageNo: currentPage.value,
    pageSize: pageSize.value
  }).then(async (res) => {
    loading.value = false
    if (res.code === 200) {
      // 获取所有发起人ID
      const initiatorIds = res.data.rows.map(row => row.initiator)

      // 获取发起人信息
      const initiatorPromises = initiatorIds.map(id => 
        baseService.get(`/sysUser/info/${id}`).then(userRes => {
          if (userRes.code === 200) {
            return {
              id: id,
              // 根据返回数据结构调整，使用 account 字段
              initiator: userRes.data.account || '-'
            }
          }
          return {
            id: id,
            initiator: '-'
          }
        }).catch(() => ({
          id: id,
          initiator: '-'
        }))
      )

      const initiatorInfos = await Promise.all(initiatorPromises)
      
      // 处理表格数据：添加发起人信息和状态
      const processedRows = res.data.rows.map(row => ({
        ...row,
        // 更新发起人字段
        initiator: initiatorInfos.find(info => info.id === row.initiator)?.initiator || '-',
        // 根据结束时间判断状态
        status: row.endTime ? '已完成' : '进行中'
      }))

      tableData.value = processedRows
      total.value = res.data.total
    } else {
      tableData.value = []
      total.value = 0
    }
  }).catch(() => {
    loading.value = false
    tableData.value = []
    total.value = 0
  })
}

// 处理维度变化
const handleDimensionChange = () => {
  timeChartDate.value = null
  updateTimeChart()
}

// 处理时间选择变化
const handleTimeChartDateChange = () => {
  updateTimeChart()
}

// 更新时效分析图表
const updateTimeChart = () => {
  const chartDom = document.getElementById('timeChart')
  if (!chartDom) return
  timeChartRef.value = echarts.init(chartDom)
  
  // 模拟数据，实际应该从API获取
  const mockData = {
    week: {
      xData: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      series: [
        {
          name: '平均耗时',
          data: [4.5, 3.8, 5.2, 4.1, 3.6, 4.8, 3.9]
        },
        {
          name: '最长耗时',
          data: [8.5, 7.8, 9.2, 7.1, 6.6, 8.8, 7.9]
        },
        {
          name: '最短耗时',
          data: [2.5, 1.8, 2.2, 2.1, 1.6, 2.8, 1.9]
        }
      ]
    },
    month: {
      xData: Array.from({length: 31}, (_, i) => `${i + 1}日`),
      series: Array(3).fill(0).map(() => ({
        data: Array.from({length: 31}, () => +(Math.random() * 6 + 2).toFixed(1))
      }))
    },
    year: {
      xData: Array.from({length: 12}, (_, i) => `${i + 1}月`),
      series: Array(3).fill(0).map(() => ({
        data: Array.from({length: 12}, () => +(Math.random() * 6 + 2).toFixed(1))
      }))
    }
  }

  const data = mockData[timeChartDimension.value]
  
  const option = {
    title: {
      left: 'center',
      top: 0,
      textStyle: {
        fontSize: 15,
        color: '#303133',
        fontWeight: 500
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(255,255,255,0.95)',
      borderColor: '#ebeef5',
      borderWidth: 1,
      padding: [8, 10],
      textStyle: {
        color: '#606266',
        fontSize: 13
      },
      formatter: (params: any[]) => {
        let html = `<div style="font-weight: 500;margin-bottom:5px;">${params[0].axisValue}</div>`
        params.forEach(item => {
          html += `<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:4px;">
            <span>${item.seriesName}：</span>
            <span style="font-weight:500;color:#303133;margin-left:15px">${item.value} 小时</span>
          </div>`
        })
        return html
      }
    },
    legend: {
      data: ['平均耗时', '最长耗时', '最短耗时'],
      bottom: 0,
      icon: 'circle',
      itemWidth: 8,
      itemHeight: 8,
      itemGap: 15,
      textStyle: {
        color: '#606266',
        fontSize: 12
      }
    },
    grid: {
      top: '10%',
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: data.xData,
      axisTick: {
        show: false
      },
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266',
        fontSize: 12,
        interval: timeChartDimension.value === 'month' ? 'auto' : 0
      }
    },
    yAxis: {
      type: 'value',
      name: '小时',
      nameTextStyle: {
        color: '#909399',
        fontSize: 12,
        padding: [0, 0, 0, 30]
      },
      splitLine: {
        lineStyle: {
          color: '#f0f0f0',
          type: 'dashed'
        }
      },
      axisLabel: {
        color: '#606266',
        fontSize: 12
      }
    },
    series: [
      {
        name: '平均耗时',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#409EFF'
        },
        lineStyle: {
          width: 2
        },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64,158,255,0.2)' },
            { offset: 1, color: 'rgba(64,158,255,0.02)' }
          ])
        },
        data: data.series[0].data
      },
      {
        name: '最长耗时',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#F56C6C'
        },
        lineStyle: {
          width: 2
        },
        data: data.series[1].data
      },
      {
        name: '最短耗时',
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 6,
        itemStyle: {
          color: '#67C23A'
        },
        lineStyle: {
          width: 2
        },
        data: data.series[2].data
      }
    ]
  }
  
  timeChartRef.value.setOption(option)
}

onMounted(() => {
  initCharts()
  getTableData()
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})
</script>

<style scoped>
.report-analysis {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 40px);
}

.box-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.main-title {
  font-size: 20px;
  font-weight: bold;
  color: #303133;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}

.left-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.right-section {
  display: flex;
  align-items: center;
  gap: 15px;
}

.chart-title {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 6px;
}

.chart-title .el-icon {
  font-size: 14px;
  color: #909399;
  cursor: help;
}

.chart-row {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
}

.chart-card {
  height: 100%;
  transition: all 0.3s;
  border-radius: 8px;
  background: #fff;
  position: relative;
}

.chart-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
}

.chart-container {
  height: 320px;
  padding: 15px 10px;
  position: relative;
}

.table-row {
  margin-top: 20px;
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.header-operations {
  display: flex;
  gap: 15px;
  align-items: center;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}

:deep(.el-card__header) {
  padding: 12px 15px;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-card__body) {
  padding: 10px;
}

:deep(.el-tag) {
  padding: 0 10px;
  height: 24px;
  line-height: 24px;
  border-radius: 12px;
}

.refresh-button {
  margin-left: 10px;
}

.auto-refresh-switch {
  margin-left: 15px;
}

.time-analysis-header {
  display: none;
}

.status-header {
  display: none;
}

.chart-header {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px 15px;
  gap: 12px;
}

.chart-title {
  font-size: 15px;
  font-weight: 500;
  color: #303133;
  display: flex;
  align-items: center;
  gap: 6px;
  height: 22px;
  line-height: 22px;
}

.chart-title .el-icon {
  font-size: 14px;
  color: #909399;
  cursor: help;
}

.filter-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-top: 8px;
}

.filter-buttons {
  display: flex;
  justify-content: center;
}

.header-title {
  display: none;
}
</style>